package server.business.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import server.business.pojo.OverallBlood;
import server.business.pojo.PatientBackInformation;
import server.business.pojo.PatientTransfusionInformation;
import server.business.pojo.ReturnedBloodIn;
import server.business.service.*;
import server.business.utils.GenerateNumberBySnowFlake;
import server.business.utils.results.zy.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 患者退血模块
 *
 * @Author 赵越
 * @Time 2022-08-03
 */
@RestController
@RequestMapping("/bloodcanclepatient")
public class BloodCanclePatientController {

    /**
     * 引入患者退血信息相关功能
     */
    @Autowired
    private PatientBackInformationService patientBackInformationService;

    /**
     * 引入患者输血信息相关功能
     */
    @Autowired
    private PatientTransfusionInformationService patientTransfusionInformationService;

    /**
     * 引入血液基础信息相关功能
     */
    @Autowired
    private BloodInformationService bloodInformationService;

    /**
     * 引入血液信息相关功能
     */
    @Autowired
    private OverallBloodService overallBloodService;

    /**
     * 引入退血入库相关功能
     */
    @Autowired
    private ReturnedBloodInService returnedBloodInService;

    /**
     * 局部解决日期转换问题
     *
     * @param binder  日期转换工具
     * @param request 监控网络请求
     */
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 是否允许退血模块
     *
     * @param number        患者病历号
     * @param transfusion   患者输血申请单号
     * @param isAllowedBack 是否允许退血（1表示允许，0表示不允许）
     * @return 返回是否允许退血结果
     */
    @RequestMapping(value = "/normal/isagree", method = RequestMethod.POST)
    @ResponseBody

    public Result bloodCancleAgree(@RequestParam("number") Integer number, @RequestParam("transfusion") String transfusion, @RequestParam("isAllowedBack") Integer isAllowedBack) {
        overallBloodService.updateIsAllowedBackByNumberAndTransfusion(number, transfusion, isAllowedBack);
        return Result.success();
    }

    /**
     * 根据患者病历号和输血单号查询患者输血信息
     *
     * @return 返回患者所有输血信息
     */
    @RequestMapping(value = "/normal/find", method = RequestMethod.GET)
    @ResponseBody

    public Result bloodCancleAgree(@RequestParam("number") Integer number, @RequestParam("transfusion") String transfusion) {
        OverallBlood all = overallBloodService.findByNumberAndTransfusion(number, transfusion);
        if (all == null) {
            return Result.error("600", "查询为空");
        } else {
            return Result.success(all);
        }
    }

    /**
     * 患者退血入库模块
     *
     * @param returnedBloodIn 退血入库信息包装类
     * @return 返回患者退血入库结果
     */
    @RequestMapping(value = "/normal/in", method = RequestMethod.POST)
    @ResponseBody

    public Result patientBloodBackIn(@RequestBody ReturnedBloodIn returnedBloodIn) {
        returnedBloodInService.returnBloodIn(returnedBloodIn);
        String number = returnedBloodIn.getBackInformationNumber();
        returnedBloodInService.setIsAllowBackByNumber(number, 0);
        returnedBloodInService.deleteBackInformationByNumber(number);
        return Result.success();
    }

    /**
     * 整体输血信息查询模块
     *
     * @param number 患者病历号
     * @return 若允许退血，返回该患者的所有输血信息；若不允许退血，返回不允许退血的信息
     */
    @RequestMapping(value = "/normal/getapplication/{currentPage}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    public Result overAllTransfusion(@RequestParam("number") Integer number, @PathVariable int currentPage, @PathVariable int pageSize) {
        int flag = 0;
        List<OverallBlood> overallBloodInformation = overallBloodService.findIsAllowBackByNumber(number);
        List<PatientTransfusionInformation> allTransfusion = new ArrayList<>();
        for (OverallBlood overallBlood : overallBloodInformation) {
            Integer isAllowedBack = overallBlood.getIsAllowedBack();
            if (isAllowedBack == 1) {
                String patientId = overallBlood.getPatientId();
                String transfusionNumber = overallBlood.getTransfusionNumber();
                PatientTransfusionInformation allTransfusionByPatientIdAndTransfusionNumber = patientTransfusionInformationService.findAllTransfusionByPatientIdAndTransfusionNumber(patientId, transfusionNumber);
                if (allTransfusionByPatientIdAndTransfusionNumber != null) {
                    flag = 1;
                    allTransfusion.add(allTransfusionByPatientIdAndTransfusionNumber);
                }
            }
        }
        if (flag == 1) {
            IPage<PatientTransfusionInformation> page = patientTransfusionInformationService.getPage(currentPage, pageSize, allTransfusion);
            // 如果当前页码值大于了总页码值，就重新执行查询操作，使用最大页码值作为当前页码值
            if (currentPage > page.getPages()) {
                page = patientTransfusionInformationService.getPage((int) page.getPages(), pageSize, allTransfusion);
            }
            if (page == null) {
                return Result.error("600", "查询为空");
            } else {
                return Result.success(page);
            }
        } else {
            return Result.error("600", "查询为空");
        }
    }

    /**
     * 患者退血申请登记模块
     *
     * @param patientBackInformation 患者退血申请信息包装类
     * @return 返回患者退血申请结果
     */
    @RequestMapping(value = "/normal/application", method = RequestMethod.POST)
    @ResponseBody

    public Result bloodCancleApplication(@RequestBody PatientBackInformation patientBackInformation) {
        patientBackInformationService.savePatientBackInformation(patientBackInformation);
        String transfusionNumber = patientBackInformation.getTransfusionNumber();
        String condition = "22";
        String number = patientBackInformation.getBackInformationNumber();
        overallBloodService.updateConditionAndNumberByTransfusionNumber(transfusionNumber, condition, number);
        patientTransfusionInformationService.setStateByTransfusionNumber(transfusionNumber, "17");
        return Result.success();
    }

    /**
     * 根据退血单号获取患者退血信息
     *
     * @param number 退血单号
     * @return 返回患者退血信息
     */
    @RequestMapping(value = "/normal/backinformation", method = RequestMethod.GET)
    @ResponseBody

    public Result bloodCanclePatientBackInformation(@RequestParam("number") String number) {
        PatientBackInformation backInformation = patientBackInformationService.getBackInformationByNumber(number);
        if (backInformation == null) {
            return Result.error("600", "查询为空");
        } else {
            return Result.success(backInformation);
        }
    }

    /**
     * 患者退血申请审批模块
     *
     * @param patientBackInformation 患者退血申请信息包装类
     * @return 返回患者退血申请审批结果
     */
    @RequestMapping(value = "/review/approval", method = RequestMethod.POST)
    @ResponseBody

    public Result bloodCanclePatientApproval(@RequestBody PatientBackInformation patientBackInformation) {
        String transfusionNumber = patientBackInformation.getTransfusionNumber();
        String bloodId = patientTransfusionInformationService.findBloodIdByTransfusionNumber(transfusionNumber);
        bloodInformationService.setConditionByBloodNumber(bloodId, "32");
        overallBloodService.updateConditionByTransfusionNumber(transfusionNumber, "18");
        overallBloodService.updateIsAllowedBackByTransfusion(transfusionNumber, 0);
        String auditor = patientBackInformation.getAuditor();
        String auditorNumber = patientBackInformation.getAuditorNumber();
        Date auditTime = patientBackInformation.getAuditTime();
        String number = patientBackInformation.getBackInformationNumber();
        patientBackInformationService.setAuditByNumber(number, auditor, auditorNumber, auditTime);
        return Result.success();
    }

    /**
     * 患者退血申请驳回模块
     *
     * @param transfusionNumber 输血单号
     * @param rejectInformation 退血驳回原因
     * @param auditor           审核人
     * @param auditorNumber     审核人工号
     * @param auditTime         审核时间
     * @param number            退血单号
     * @return 返回患者退血申请驳回结果
     */
    @RequestMapping(value = "/review/reject", method = RequestMethod.POST)
    @ResponseBody

    public Result bloodCanclePatientReject(@RequestParam("transfusionNumber") String transfusionNumber, @RequestParam("rejectInformation") String rejectInformation, @RequestParam("auditor") String auditor, @RequestParam("auditorNumber") String auditorNumber, @RequestParam("auditTime") String auditTime, @RequestParam("backInformationNumber") String number) {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
        Date dd = null; //将字符串改为date的格式
        try {
            dd = sdf.parse(auditTime);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        String resDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dd);
        overallBloodService.updateConditionByTransfusionNumber(transfusionNumber, "20");
        overallBloodService.setRejectInformationByTransfusionNumber(transfusionNumber, rejectInformation);
        patientBackInformationService.setAuditByNumber(number, auditor, auditorNumber, dd);
        return Result.success();
    }

    /**
     * 患者退血申请退费模块
     *
     * @param patientBackInformation 患者退血信息表包装类
     * @return 患者退血申请退费结果
     */
    @RequestMapping(value = "/normal/moneycancle", method = RequestMethod.POST)
    @ResponseBody
    public Result bloodCanclePatientMoneyCancle(@RequestBody PatientBackInformation patientBackInformation) {
        String number = patientBackInformation.getBackInformationNumber();
        patientBackInformationService.setInformationByNumber(number, patientBackInformation);
        overallBloodService.setConditionByNumber(number, "19");
        return Result.success();
    }

    /**
     * 得到退血审核通过的血液信息
     *
     * @param currentPage  当前页码
     * @param pageSize     当前页个数
     * @param overallBlood 整体输血信息
     * @return 返回退血审核通过的血液信息
     */
    @RequestMapping(value = "/normal/getpass/{currentPage}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    public Result getPassBloodInformation(@PathVariable int currentPage, @PathVariable int pageSize, OverallBlood overallBlood) {
        IPage<OverallBlood> page = overallBloodService.getPage(currentPage, pageSize, overallBlood);
        //如果当前页码值大于了总页码值，就重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = overallBloodService.getPage((int) page.getPages(), pageSize, overallBlood);
        }
        if (page == null) {
            return Result.error("600", "查询为空");
        } else {
            return Result.success(page);
        }
    }

    /**
     * 患者退血申请查询模块
     *
     * @param currentPage            当前页
     * @param pageSize               页面大小
     * @param patientBackInformation 患者退血信息
     * @return 返回所有患者的退血申请查询结果
     */
    @RequestMapping(value = "/normal/findback/{currentPage}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    public Result bloodCanclePatientFindInformation(@PathVariable int currentPage, @PathVariable int pageSize, PatientBackInformation patientBackInformation) {
        IPage<PatientBackInformation> page = patientBackInformationService.getPage(currentPage, pageSize, patientBackInformation);
        // 如果当前页码值大于了总页码值，就重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = patientBackInformationService.getPage((int) page.getPages(), pageSize, patientBackInformation);
        }
        if (page == null) {
            return Result.error("600", "查询为空");
        } else {
            return Result.success(page);
        }
    }

    /**
     * 返回所有已经退血退费完成的退血信息
     *
     * @param currentPage 当前页面
     * @param pageSize    当前页面大小
     * @return 返回所有已经退血退费完成的退血信息
     */
    @RequestMapping(value = "/normal/findbackcondition/{currentPage}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    public Result bloodCanclePatientFindBackInformationByCondition(@PathVariable int currentPage, @PathVariable int pageSize) {
        int flag = 0;
        List<OverallBlood> bloodInformationByCondition = overallBloodService.getBloodInformationByCondition("19");
        List<PatientBackInformation> allBackInformation = new LinkedList<>();
        for (OverallBlood overallBlood : bloodInformationByCondition) {
            String number = overallBlood.getBackInformationNumber();
            PatientBackInformation data = patientBackInformationService.getBackInformationByNumber(number);
            if (data != null) {
                flag = 1;
                allBackInformation.add(data);
            }
        }
        if (flag == 1) {
            IPage<PatientBackInformation> page = patientBackInformationService.getPageIn(currentPage, pageSize, allBackInformation);
            if (currentPage > page.getPages()) {
                page = patientBackInformationService.getPageIn((int) page.getPages(), pageSize, allBackInformation);
            }
            if (page == null) {
                return Result.error("600", "查询为空");
            } else {
                return Result.success(page);
            }
        } else {
            return Result.error("600", "查询为空");
        }
    }

    /**
     * 生成患者退血单号
     *
     * @param id 编号
     * @return 返回生成的患者退血单号
     */
    @RequestMapping(value = "/normal/getbacknumber", method = RequestMethod.GET)
    @ResponseBody
    public Result getBackNumber(@RequestParam("id") Integer id) {
        GenerateNumberBySnowFlake backNumber = new GenerateNumberBySnowFlake(id, "No.");
        String res = backNumber.genNumberByflag();
        return Result.success(res);
    }

    /**
     * 患者输血信息批量打印
     *
     * @param ids 编号列表
     */
    @GetMapping(value = "normal/batchdownloadpba")
    @ResponseBody
    public void batchDownloadPba(HttpServletResponse response, @RequestParam ArrayList<Long> ids) throws IOException {
        patientTransfusionInformationService.batchDownload(response, ids);
    }

    /**
     * 患者退血信息批量打印
     *
     * @param ids 编号列表
     */
    @GetMapping(value = "normal/batchdownloadpbaar")
    @ResponseBody
    public void batchDownloadPbaar(HttpServletResponse response, @RequestParam ArrayList<Long> ids) throws IOException {
        patientBackInformationService.batchDownload(response, ids);
    }

    /**
     * 患者退血入库信息批量打印
     *
     * @param ids 编号列表
     */
    @GetMapping(value = "normal/batchdownloadpbs")
    @ResponseBody
    public void batchDownloadPbs(HttpServletResponse response, @RequestParam ArrayList<Long> ids) throws IOException {
        patientBackInformationService.batchDownloadIn(response, ids);
    }

    /**
     * 患者退血退费信息批量打印
     *
     * @param ids 编号列表
     */
    @GetMapping(value = "normal/batchdownloadbpm")
    @ResponseBody
    public void batchDownloadBbm(HttpServletResponse response, @RequestParam ArrayList<Long> ids) throws IOException {
        overallBloodService.batchDownload(response, ids);
    }

}
